package xyz.ibenben.zhongdian.system.controller.sys;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import net.sf.json.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import xyz.ibenben.zhongdian.common.annotation.SystemControllerLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.system.controller.BaseController;
import xyz.ibenben.zhongdian.system.entity.sys.SysResource;
import xyz.ibenben.zhongdian.system.entity.sys.SysRole;
import xyz.ibenben.zhongdian.system.entity.sys.SysRoleResources;
import xyz.ibenben.zhongdian.system.entity.sys.SysUser;
import xyz.ibenben.zhongdian.system.form.sys.SysRoleForm;
import xyz.ibenben.zhongdian.system.service.CompanyInfoService;
import xyz.ibenben.zhongdian.system.service.sys.SysResourcesService;
import xyz.ibenben.zhongdian.system.service.sys.SysRoleResourcesService;
import xyz.ibenben.zhongdian.system.service.sys.SysRoleService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

/**
 * 系统角色控制类
 * 提供了一些基本的服务，如初始化、获取角色列表等方法。
 * spring mvc思想 通过controller来调用service里的方法，
 * service里的方法再通过调用Dao来实现对数据的操作
 * 返回值统统是String类型的返回页面有统一的安排方便代码提取
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Controller
@SessionAttributes("sysRoleForm")
@RequestMapping("/sys/sysRole")
public class RoleController extends BaseController {
    /**
     * 实体名称
     */
    private static final String ENTITYNAME = "sysRole";

    @Resource
    private SysRoleService roleService;
    @Resource
    private SysRoleResourcesService roleResourcesService;
    @Resource
    private SysResourcesService resourcesService;
    @Resource
    private CompanyInfoService companyInfoService;

    /**
     * 初始化
     *
     * @param map         参数
     * @param sysRoleForm 条件参数
     */
    @ModelAttribute
    public void init(Model map, @ModelAttribute SysRoleForm sysRoleForm, HttpSession session) {
        map.addAttribute("companyInfoList", companyInfoService.selectAll());
        SysRoleForm newSysRoleForm = new SysRoleForm();
        if (sysRoleForm != null) {
            newSysRoleForm = sysRoleForm;
        }
        SysUser user = (SysUser) session.getAttribute(Constants.SESSION);
        if (user != null && user.getSysRole() != null) {
            newSysRoleForm.setCompanyId(user.getSysRole().getCompanyId());
        }
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), newSysRoleForm);
    }

    /**
     * 获取角色列表
     *
     * @param map         参数
     * @param sysRoleForm 条件参数
     * @return 页面
     */
    @RequestMapping(value = "/getAll")
    @SystemControllerLog(description = "获取角色列表")
    public String getAll(Model map, @ModelAttribute SysRoleForm sysRoleForm) {
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), sysRoleForm);
        Page<SysRole> page = PageHelper.startPage(sysRoleForm.getPageIndex(), sysRoleForm.getPageSize());
        List<SysRole> list = roleService.findAll(sysRoleForm);
        map.addAttribute(String.format(Constants.LISTENTITY, ENTITYNAME), list);
        map.addAttribute(Constants.PI, page.toPageInfo());
        return "sys/" + String.format(Constants.LISTPAGE, ENTITYNAME);
    }

    /**
     * 删除角色记录
     *
     * @param id      主键
     * @param request 请求
     * @return 页面
     */
    @RequestMapping(value = "/delete")
    @SystemControllerLog(description = "删除角色记录")
    public String delete(@RequestParam("id") Long id, HttpServletRequest request, SessionStatus status) {
        roleService.delete(id, request);
        status.setComplete();
        return String.format(Constants.REDIRECT, "sys/" + ENTITYNAME);
    }

    /**
     * 删除角色列表
     *
     * @param sysRoleForm 条件参数
     * @param request     请求
     * @return 页面
     */
    @RequestMapping("/deleteAll")
    @SystemControllerLog(description = "删除角色列表")
    public String deleteAll(@ModelAttribute SysRoleForm sysRoleForm, HttpServletRequest request, SessionStatus status) {
        if (sysRoleForm.getSelectIds() != null) {
            String[] ids = sysRoleForm.getSelectIds().split(Constants.COMMA);
            for (String id : ids) {
                roleService.delete(Long.parseLong(id), request);
            }
        }
        status.setComplete();
        return String.format(Constants.REDIRECT, "sys/" + ENTITYNAME);
    }

    /**
     * 打开角色添加页面
     *
     * @param map 参数
     * @return 页面
     */
    @GetMapping("/add")
    @SystemControllerLog(description = "打开角色添加页面")
    public String openAddPage(Model map) {
        map.addAttribute(ENTITYNAME, new SysRole());
        return "sys/" + String.format(Constants.ADDPAGE, ENTITYNAME);
    }

    /**
     * 保存角色添加记录
     *
     * @param sysRole       实体
     * @param bindingResult 校验
     * @param request       请求
     * @return 页面
     */
    @PostMapping("/add")
    @SystemControllerLog(description = "保存角色添加记录")
    public String postAddMessage(@Valid @ModelAttribute(ENTITYNAME) SysRole sysRole,
                                 BindingResult bindingResult, HttpServletRequest request, SessionStatus status) {
        SysRole role = roleService.selectByRoleDesc(sysRole.getCompanyId(), sysRole.getRoleDesc());
        if (null != role) {
            bindingResult.rejectValue("roleDesc", "misFormat", "这个角色名称已经存在了！请更改!");
            return "sys/" + String.format(Constants.ADDPAGE, ENTITYNAME);
        }
        if (!bindingResult.hasErrors()) {
            roleService.save(sysRole, request);
            status.setComplete();
            return String.format(Constants.REDIRECT, "sys/" + ENTITYNAME);
        } else {
            return "sys/" + String.format(Constants.ADDPAGE, ENTITYNAME);
        }
    }

    /**
     * 浏览角色记录
     *
     * @param map         参数
     * @param id          主键
     * @param sysRoleForm 条件参数
     * @return 页面
     */
    @GetMapping("/view")
    @SystemControllerLog(description = "浏览角色记录")
    public String openViewPage(Model map, @RequestParam Long id, @ModelAttribute SysRoleForm sysRoleForm) {
        map.addAttribute(ENTITYNAME, roleService.selectRoleWithCompanyById(id));
        return "sys/" + String.format(Constants.VIEWPAGE, ENTITYNAME);
    }

    /**
     * 打开获取资源列表
     *
     * @param id  主键
     * @param map 参数
     * @return 页面
     */
    @RequestMapping("/resources")
    @SystemControllerLog(description = "打开获取资源列表")
    public String resources(@RequestParam Long id, Model map) {
        map.addAttribute("roleId", id);
        List<SysResource> resourcesList = resourcesService.queryResourcesListWithSelected(id);
        map.addAttribute("resourcesList", JSONArray.fromObject(resourcesList));
        return "sys/sysRole/resources";
    }

    /**
     * 分配角色
     *
     * @param roleId      参数
     * @param resourcesId 参数
     * @return 页面
     */
    @RequestMapping("/saveRoleResources")
    @SystemControllerLog(description = "保存资源记录")
    public String saveRoleResources(@RequestParam("roleId") Long roleId,
                                    @RequestParam("resourcesId") String resourcesId, SessionStatus status) {
        SysRoleResources srr = new SysRoleResources();
        srr.setRoleId(roleId);
        srr.setResourcesIds(resourcesId);
        roleResourcesService.addRoleResources(srr);
        status.setComplete();
        return String.format(Constants.REDIRECT, "sys/" + ENTITYNAME);
    }

}
